import React, { useEffect, useState } from 'react'
import './index.css'
import { List, Typography } from 'antd'
import CartItem from './CartItem'

const Cart = () => {
    const [cartData, setCartData] = useState(Array(5)
        .fill(undefined)
        .map((v, i) => ({
            id: i,
            name: `商品${i}`,
            checked: false,
            price: Math.round(Math.random() * 100)
        }))
    )
    const [total, setTotal] = useState(0);
    const [checkedAll, setCheckedAll] = useState(false);
    const onCheckedChange = (item) => {
        let idx = cartData.findIndex(data => item.id == data.id)
        cartData[idx].checked = !cartData[idx].checked;
        setCartData([
            ...cartData
        ])
        // console.log(item)
    }
    const onWrappCheckedAllChange = (e) => {
        // setCheckedAll(!checkedAll)
        let newData = cartData.map((item) => {
            item.checked = !item.checked;
            return item;
        })
        setCartData([...cartData])
    }
    // console.log(cartData)
    const Footer = (
        <div className="footer">
            <div className="check-all">
                <input
                    checked={checkedAll}
                    type="checkbox"
                    onChange={onWrappCheckedAllChange}
                    name=""
                    id="" />
                全选
            </div>
            <div>
                价格总计<Typography.Text mark>${total}</Typography.Text>
            </div>
        </div>
    )
    useEffect(() => {
        // mounted 挂载好的
        // update
        let tolalPrice = cartData
            .filter(item => item.checked)
            .reduce((prev, item) => {
                console.log(item);
                return prev + item.price;
            }, 0)
        setTotal(tolalPrice);
        let isAll = cartData
            .every(item => item.checked)
        setCheckedAll(isAll)
        console.log(isAll)
    }, [cartData])
    return (
        <div className='cart'>
            <List
                header={<div>购物车</div>}
                footer={Footer}
                bordered
                dataSource={cartData}
                renderItem={item => {
                    return (
                        <List.Item>
                            <CartItem
                                item={item}
                                onCheckedChange={onCheckedChange}
                            />
                        </List.Item>
                    )
                }}
            />
        </div>
    )
}

export default Cart